package my2Cents;

import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;

import net.phys2d.raw.Body;
import net.phys2d.raw.CustomCollider;

public class Spawner extends Body implements SpecialBody, CustomCollider {
	private BodyState state;
	private int keySpawn;
	private boolean spawning = false;
	private int lifeSpan;
	private boolean isStatic = false;
	
	public Spawner(Body instance) {
		super(instance.getShape(), instance.getMass());
		state = new BodyState(instance);
		state.resolveBody(this);
		this.setDrawColor(new Color(20,75,255));
	}

	public boolean allowCollision(Body other) {
		if(other.getTempData("spawned") != null) return false;
		return true;
	}
	
	public void spawn() {
		final Body b = state.getNewBody();
		b.setRotation(this.getRotation());
		b.setPosition(this.getPosition().getX(),
					  this.getPosition().getY());
		b.attachTempData("spawned", true);
		
		Sandbox.getWorld().add(b);
		Sandbox.getUndoList().add(new Undo(b,Sandbox.getWorld(),"Spawned Object") {
			public void performUndo() {
				Body bod = (Body) this.getObject();
				Sandbox.getWorld().remove(bod);
			}
		});
		
		//addExcludedBody(b);
		
		if(lifeSpan > 0) {
			long delay = lifeSpan*1000;
			Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					Sandbox.getWorld().remove(b);
				}		
			}, delay);
		}
	}
	
	public void setSpawnCode(int c) {
		keySpawn = c;
	}
	
	public void think() {
		super.think();
		if(Sandbox.keyIsDown(keySpawn)) {
			if(!spawning) {
				spawning = true;
				spawn();
			}
		} else {
			spawning = false;
		}
	}

	public void setBodyLifeSpan(int timer) {
		lifeSpan = timer;
	}

	public Body getTemplate() {
		return state.getBody();
	}

	public Body duplicate() {
		Spawner n = new Spawner(getTemplate());
		n.keySpawn = keySpawn;
		n.lifeSpan = lifeSpan;
		n.setStatic(this.isStatic);
		return n;
	}

	public void setStatic(boolean createStatic) {
		if(isStatic != createStatic) {
			if(createStatic) {
				this.setShouldCollide(false);
				set(getShape(),Body.INFINITE_MASS);
			} else {
				this.setShouldCollide(true);
				set(getShape(),getTemplate().getMass());
			}
			state.resolveBody(this);
			this.setDrawColor(new Color(20,75,255));
		}
		isStatic = createStatic;
	}
	
	public boolean isMoveable() {
		if(isStatic) return false;
		return super.isMoveable();
	}
	
	public boolean isStatic() {
		return isStatic;
	}
	
	public boolean isResting() {
		if(isStatic) return true;
		return super.isResting();
	}
}
